package com.fastloan.common.datasource;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author chenkai
 * createTime 2017-12-2017/12/13 13:45
 */
public class DynamicDaraSource extends AbstractRoutingDataSource {
    //写数据源
    private Object writeDataSource;

    //读数据源
    private List<Object> readDataSourceList;

    //读数据源个数
    private int readDataSourceSize;

    //获取读数据源方式，0：随机，1：轮询
    private int readDataSourcePollPattern = 0;

    private AtomicLong counter = new AtomicLong(0);

    private static final Long MAX_POOL = Long.MAX_VALUE;

    private final Lock lock = new ReentrantLock();

    public int getReadDataSourcePollPattern() {
        return readDataSourcePollPattern;
    }

    public void setReadDataSourcePollPattern(int readDataSourcePollPattern) {
        this.readDataSourcePollPattern = readDataSourcePollPattern;
    }

    public AtomicLong getCounter() {
        return counter;
    }

    public void setCounter(AtomicLong counter) {
        this.counter = counter;
    }

    public static Long getMaxPool() {
        return MAX_POOL;
    }

    public Lock getLock() {
        return lock;
    }

    public int getReadDataSourceSize() {
        return readDataSourceSize;
    }

    public void setReadDataSourceSize(int readDataSourceSize) {
        this.readDataSourceSize = readDataSourceSize;
    }

    public Object getWriteDataSource() {
        return writeDataSource;
    }

    public void setWriteDataSource(Object writeDataSource) {
        this.writeDataSource = writeDataSource;
    }

    public List<Object> getReadDataSourceList() {
        return readDataSourceList;
    }

    public void setReadDataSourceList(List<Object> readDataSourceList) {
        this.readDataSourceList = readDataSourceList;
    }

    @Override
    public void afterPropertiesSet() {
        if (this.writeDataSource == null) {
            throw new IllegalArgumentException("未找到写入数据源");
        }
        //设置默认数据源
        setDefaultTargetDataSource(writeDataSource);
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DynamicDataSourceGlobal.WRITE.name(), writeDataSource);
        if (readDataSourceList != null && !readDataSourceList.isEmpty()) {
            for (int i = 0; i < readDataSourceList.size(); i++) {
                targetDataSources.put(DynamicDataSourceGlobal.READ.name() + i, readDataSourceList.get(i));
            }
            readDataSourceSize = readDataSourceList.size();
        }
        setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
    }

    //获取数据源的key
    @Override
    protected Object determineCurrentLookupKey() {
        DynamicDataSourceGlobal dataSource = DataSourceHolder.getDataSource();
        if (dataSource == null || dataSource == DynamicDataSourceGlobal.WRITE || readDataSourceSize <= 0) {
            return DynamicDataSourceGlobal.WRITE.name();
        }
        int index;
        if (readDataSourcePollPattern == 1) {
            //轮询方式
            long currValue = counter.incrementAndGet();
            if ((currValue + 1) >= MAX_POOL) {
                try {
                    lock.lock();
                    if ((currValue + 1) >= MAX_POOL) {
                        counter.set(0);
                    }
                } finally {
                    lock.unlock();
                }
            }
            index = (int) (currValue % readDataSourceSize);
        } else {
            //随机方式
            index = ThreadLocalRandom.current().nextInt(0, readDataSourceSize);
        }
        return DynamicDataSourceGlobal.READ.name() + index;
    }

}
